import json
from typing import List
from string import Template
from model import *
from parse import *

class Exporter:
    def preprocess(self, note_list:List):
        """预处理，只取笔记和标注"""
        res = dict()

        for note in note_list:
            if isinstance(note, Bookmark):
                continue
            if note.book not in res:
                res[note.book] = {'comments':dict(),'highlights':dict()}
            comments = res[note.book]['comments']
            highlights = res[note.book]['highlights']
            if isinstance(note, Comment):
                comments[note.position.start] = note
            elif isinstance(note, Highlighting):
                highlights[note.position.start] = note
            else:
                l.fatal('unexpected type: %s' % (type(note)))
                sys.exit(-1)
        return res



class MarkdownExporter(Exporter):
    note_template = Template('\n\n> ${reference}\n\n```\n${comment}\n```\n\n${time}\n')
    note_template2 = Template('\n\n> ${reference}\n\n${time}\n')
    def __init__(self):
        pass

    def export(self, note_list, output_filename):
        """按照书名分类，输出为markdown文本"""
        sections = dict()
        out = open(output_filename, 'w')
        assert(out)

        data = self.preprocess(note_list)
        for book,booknote in data.items():
            highlights = booknote['highlights']
            comments = booknote['comments']
            out.write(f'## {book}')
            for highlight in highlights.values():
                comment = None
                if highlight.position.start in comments:
                    comment = comments[highlight.position.start]
                s = self._export_entry(highlight, comment)
                out.write(s)
            out.write(f'\n\n')
            out.flush()
        out.close()

    def _export_entry(self, note:Note, comment=None):
        if comment is not None:
            return self.note_template.substitute(
                    reference=note.content,
                    comment=comment.content,
                    time=str(comment.time))
        return self.note_template2.substitute(
                    reference=note.content,
                    time=str(note.time))

class JsonExporter:
    def __init__(self):
        pass
    def export(note_list, output_filename):
        pass


class HtmlExporter(Exporter):
    template1 = Template('<blockquote class="highlight"><pre>${highlight}</pre><br><small>—— ${footnote}</small></blockquote><hr>')
    template2 = Template('<blockquote class="highlight"><pre>${highlight}</pre><br><small>${footnote}</small></blockquote><p class="comment">${comment}</p><hr>')
    def __init__(self, template_filename):
        self.t_filename = template_filename

    def export(self, note_list, output_filename):
        # 读取模板
        with open(self.t_filename, 'r') as f:
            template = f.read()

        # 生成内容
        content = ''
        self.preprocess(note_list)
        data = self.preprocess(note_list)
        for book,booknote in data.items():
            highlights = booknote['highlights']
            comments = booknote['comments']
            content += (f'<h2>{book}</h2>')
            for highlight in highlights.values():
                comment = None
                if highlight.position.start in comments:
                    comment = comments[highlight.position.start]
                s = self._export_entry(highlight, comment)
                content += s

        html = template.replace('%%content%%', content)

        with open(output_filename, 'w') as f:
            f.write(html)

    def _export_entry(self, note:Note, comment=None):
        time_str = note.time.strftime('%Y年%m月%d日 %H:%M:%S')
        position_str = note.position.export()
        footnote = time_str + ' | ' + position_str
        if comment is not None:
            return self.template2.substitute(
                    highlight=note.content,
                    comment=comment.content,
                    footnote=footnote)
        return self.template1.substitute(
                    highlight=note.content,
                    footnote=footnote)


class KindleExporter:
    def __init__(self):
        pass

if __name__ == '__main__':
    note_list = parse('./My Clippings.txt')
    export = HtmlExporter('./template.html')
    export.export(note_list, 'a.html')
